<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\PayRequest;
use App\Models\Order;
use App\Services\OrderService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Psr\Http\Message\ResponseInterface;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Exception\InvalidParamsException;
use Yansongda\Pay\Pay;

class PayController extends Controller
{
    /**
     * @return ResponseInterface
     * @throws InvalidParamsException
     */
    public function wechat()
    {
        try {
            Pay::config(config('pay'));
            $result = Pay::wechat()->callback();
            $result = $result->toArray();
//            $str = '{"id":"fd70239d-d5f7-56d4-83ad-983f5586fe5b","create_time":"2022-03-30T14:12:32+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":{"mchid":"1622694473","appid":"wxf2cd5395f7d412fb","out_trade_no":"20220330141226001245","transaction_id":"4200001322202203303578592949","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"ABC_CREDIT","attach":"","success_time":"2022-03-30T14:12:32+08:00","payer":{"openid":"oc2sW5FA9jJOlNql4YKyk-R0qDog"},"amount":{"total":10,"payer_total":10,"currency":"CNY","payer_currency":"CNY"}},"associated_data":"transaction","nonce":"VKe7G0aJJuM2"}}';
//            $result = json_decode($str, true);
            $trade_state = $result['resource']['ciphertext']['trade_state'] ?? '';//支付结果
            if ($trade_state == 'SUCCESS') {
                app(OrderService::class)->paySuccess($result['resource']['ciphertext']['out_trade_no'], $result['resource']['ciphertext']['transaction_id'], Carbon::parse($result['resource']['ciphertext']['success_time'])->toDateTimeString(), $result);
            }
            return Pay::wechat()->success();
        } catch (ContainerException $e) {
            info('微信支付回调失败，错误信息：' . $e->getMessage(),);
        }
    }

    /**
     * 支付宝支付回调
     * @return ResponseInterface
     * @throws InvalidParamsException
     */
    public function ali()
    {
        try {
            Pay::config(config('pay'));
            $result = Pay::alipay()->callback();
            $result = $result->toArray();
            if ($result['trade_status'] == 'TRADE_SUCCESS') {
                app(OrderService::class)->paySuccess($result['out_trade_no'], $result['trade_no'], $result['gmt_payment'], $result);
            }
            return Pay::alipay()->success();
        } catch (ContainerException $e) {
            info('支付宝回调失败，错误信息：' . $e->getMessage(),);
        }
    }


    //订单支付检测
    public function check(PayRequest $request)
    {
        $order = Order::query()->where('order_no', $request->get('order_no'))
            ->where('user_id', $request->user()->id)
            ->first();
        if (!$order) {
            return failReturn('参数错误');
        }
        return successReturn([
            'pay' => $order->pay,
        ]);
    }
}
